#include "DiskServer.h"
#include <thread>
#include "ConfigApi.h"
#include "HttpCmdProcess.h"
#include "Protocol/ProtocolApi.h"
#include "DiskController.h"
#include "log.h"


using namespace Protocol;

using namespace ConfigApi;

DiskServer *DiskServer::sm_DiskServer = nullptr;
mutex DiskServer::sm_instanceLock;

DiskServer *DiskServer::instance(){
    if(sm_DiskServer == nullptr){
        lock_guard<mutex> lock(sm_instanceLock);
        sm_DiskServer = new DiskServer();
    }
    return sm_DiskServer;
}


DiskServer::DiskServer(){
    RegistRPC();
}

DiskServer::~DiskServer(){
}

void DiskServer::RegistRPC(){
    RPCMethodMap method_map;
    method_map.emplace("GetDiskSpace", CRPCFuntion::CreateRpc([this](const Json::Value &request, const BufferMap::Ptr &inMap, Json::Value &response, BufferMap::Ptr &outMap){
		return GetDiskSpace(request, inMap, response, outMap);
	}));

	IProtocolInterface::GetInstance()->RegistProtocol("DiskServer", method_map);
}


bool DiskServer::GetDiskSpace(const Json::Value &request, const Fdt::BufferMap::Ptr &inMap, Json::Value &response, Fdt::BufferMap::Ptr &outBuffer){
    unsigned long long usedSpace = 0;
    unsigned long long totalSpace = 0;
    std::string path;
    if(!DiskController::instance()->setRealTimeRootPath()){
        LOG_PrintError("faild get root path\n");
        return false;
    }
    DiskController::instance()->getRealTimeRootPath(path);
    DiskController::instance()->getDiskSpaceInfo(path, usedSpace, totalSpace);
    unsigned long long dirSize = DiskController::instance()->calculateFolderSize(path + "/streamer");
    response["data"]["Param"]["UsableDiskSpace"] = usedSpace + dirSize;
    response["data"]["Param"]["TotalDiskSpace"] = totalSpace;
    return true;
}



